import React from 'react'
import request from '@/utils/request'
import { Table, Button,Popconfirm,message ,Image ,Input,Row,Col,Select,Space} from 'antd'
import confirm from 'antd/lib/modal/confirm';
const { Search } = Input;
const {Option}=Select
class List extends React.Component {
    state = {
        current:1,
        keyword:'',
        statu:1,
        page: 1,
        size: 10,
        type: null,
        zt:null,
        datalist: [],
        total: 0,
        selectIds: [],
        loading:false,
    }
    //请求总数
    getData = async () => {
        this.setState({
            loading:true,
        })
        const { page, size } = this.state;
        const { data } = await request.get('/goods/list', {
            params: {
                page,
                size
            }
        })
        // console.log('data=', data)
        this.setState({
            datalist: data.data,
            total: data.total,
            loading: false,
        })
    }
    //查询功能
    searchdata = async () => {       
          this.setState({
            loading:true
        })
            const { page, size } = this.state;
      const {data} =await request.post('/goods/search', {
          keyword: this.state.keyword,
          page,
          size
      })
      console.log('data1',data);
        if (data) {
            this.setState({
            datalist: data.data,
            total: data.total,
            loading: false,
            statu:3,
        })
      }
    }
    //查分类
    typedata = async () => {
   //type和zt都是分类（现代言情完结/现代言情连载）
        const { page, size, type, zt } = this.state;
        // console.log('xx=',type,zt,page,size)
        if (!type && !zt) {
            console.log('null')
            this.getData()
            return
        }
        var arr=[]
        if (type) {
            arr.push(type)
        }
        if (zt) {
            arr.push(zt)
        }
    //    this.setState({
    //         loading:true
    //     })
      const {data} =await request.post('/goods/type', {
          type:arr,
          page,
          size
      })
        if (data.total>=0) {
             this.setState({
            datalist: data.data,
            total: data.total,
            loading: false,
            statu:3,
        })
      }
    }
    //完结小说
    handleChange=(value)=> {
        console.log(`selected ${value}`);
        if (value.indexOf('全部') != -1) {
            console.log('xxxxx')
            value=null
        }
        this.setState({
            type: value,
            page: 1,
            current:1,
        },()=>{this.typedata()})
    }
    //连载小说
    handleChange1 = (value) => {
          if (value.indexOf('全部') != -1) {
              value = null
                
        }
        this.setState({
            zt: value,
            page: 1,
                current:1
        },()=>{this.typedata()})
      
    }
   //删除所选功能
    delete = async () => {
        const {selectIds} = this.state;
        const { data } = await request.post('goods/del',{
           _id:selectIds
       })
       if(data.code=== 200){
           message.success('删除成功');
           this.setState({
             selectIds:[]
           })
           this.getData();
           
       }
    }
    //删除单个的
    removeItem = (id) => {
        // console.log('id=',id)
        const arr = [id]
        this.setState({
            selectIds: arr,
        
        }, () => {
            this.delete()
        })
        
    }
    //跳转到编辑页面
    editItem = (id) => {
        const { history, location, match } = this.props;
        // console.log('editItem',id,match,location)
        history.push(match.path.replace('/list','') + '/edit/' + id);
    }
   

    componentDidMount() {

        this.getData();

    }
    //如果填写的是空，则返回，否则调用searchdata函数
    onSearch = (value) => {
        if(value=='')return
        this.setState({
            keyword: value,
            page: 1,
            current:1,
        },()=>{this.searchdata()})
   
    }
    render() {
        const { datalist, total, size ,loading,selectIds} = this.state;

        // 定义表格列
        const columns = [
            {
                // 设置表头
                title: '小说名称',
                // 设置当前列显示什么数据
                dataIndex: 'title',
                // key: 'name',
                with:80,
                render: (text, row) => {
                    return (
                        <>
                            <h4>《{text}》</h4>
                        </>
                    )
                }
            },
               {
                title: '封面',
                dataIndex: 'img_url',
                width: 80,
                render: (text, row, index) => {
                    // text: dataIndex字段对应的数据（如不设定dataIndex，则text为单条数据）
                    // row: 单条数据
                    // index: 当前数据对应的索引值
                    return   <Image
      src={text}
    />
                }
            },
            {
                title: '作者',
                dataIndex: 'autho',
                width: 100,
                render: (text, row, index) => {
                    // text: dataIndex字段对应的数据（如不设定dataIndex，则text为单条数据）
                    // row: 单条数据
                    // index: 当前数据对应的索引值
                    return <p>{text}</p>
                }
            },
              {
                title: '简介',
                dataIndex: 'introduction',
                  width: 300,
                  ellipsis: true,
                render: (text, row, index) => {
                    // text: dataIndex字段对应的数据（如不设定dataIndex，则text为单条数据）
                    // row: 单条数据
                    // index: 当前数据对应的索引值
                    return <p>{text}</p>
                }
            },
            {
                title: '类型',
                dataIndex: 'type',
                // width: 120,
                render(text) {
                    return<p>{text}</p>
                }
            },
            {
                title: '操作',
                // width: 140,
                render: (row) => {
                    return (
                        // <React.Fragment>
                        <>
                            <Button type="primary" size="small" ghost onClick={this.editItem.bind(this,row._id)}>编辑</Button>
                            <Popconfirm title="确认删除" onConfirm={
                                ()=>{
                                    this.removeItem(row._id)
                                }
                            }>
                                <Button size="small" danger>删除</Button>

                            </Popconfirm>
                        </>
                        //</React.Fragment>
                    )
                }
            }
        ]
        //全选框
        const rowSelection = {
            type: 'checkbox',
            onChange: (selectedRowKeys, selectedRows) => {
                console.log('select', selectedRowKeys, selectedRows)
                // const newdata=[...this.state.selectIds,...selectedRowKeys]
                this.setState({
                    selectIds: selectedRowKeys
                },()=>{console.log('select2', this.state.selectIds)})

            }
        }
        //分页器
        const pagination = {
            current:this.state.current,
            size: "small",
            total: total,
            pageSize: size,
            loading: loading,
            showTotal(total, range) {
                return `共${total}篇小说`
            },
            showSizeChanger: true,
            onChange: (page, pageSize) => {
                console.log('onchange', page, pageSize)

                // setState()为异步修改
                this.setState({
                    current:page*1,
                    page,
                    size: pageSize,
                }, () => {
                    // 必须要等待page或size修改完成后再发起请求
                    //等于不同的数字，调用不同的函数，得到所对应的数据
                    const { statu } = this.state
                    if (statu == 1) {
                       this.getData();
                    }
                    if (statu == 2) {
                        this.searchdata()
                    }
                    if (statu == 3) {
                        this.typedata()
                    }
                  
                })
            }
        }
        const value = ['全部', '现代言情','古代言情','玄幻言情','仙侠奇缘','悬疑','科幻空间','游戏竞技','短篇小说','轻小说']
        return (
            <div>
                <div>
                      <Row>
                        <Col flex={1}>
                        <Search placeholder="搜索作者或作品名"
                        loading={loading}
                                onSearch={(value) => {
                                    this.setState({
                                current:1,
                            },()=>{ this.onSearch(value)})
                           
                                }}
                                onChange={(e) => {
                                    if (e.target.value == '') {
                                        this.getData()
                                    }
                                }}
                        enterButton style={{ width: '200px', marginBottom: '10PX' }}
                    /></Col>
                        <Col flex={4}>
                       
                       <label htmlFor="">分类：</label>     <Select defaultValue="全部" style={{ width: 120 ,marginRight:30}} onChange={this.handleChange}>
                                {value.map(item => {
                                 return    <Option value={item}>{item}</Option>
                           })}
                            </Select>
                            <label htmlFor="">状态：</label>  <Select defaultValue="全部" style={{ width: 120 ,marginRight:30}} onChange={this.handleChange1}>
                             <Option value='全部'>全部</Option>
                             <Option value='已完结'>已完结</Option>
                             <Option value='连载中'>连载中</Option>
                            </Select>
                            <p  style={{float:'right'}}>
                                <label htmlFor="">已选中 <span style={{ color: 'red' }}>{selectIds.length}</span> 条数据   </label><Button type="danger"
                                    style={{marginLeft:3}}
                                    onClick={() => {
                                if (!selectIds.length) {
                           message.warning('请选择需要删除的数据');
                        }else{this.delete()}}}>删除所选</Button>
                            </p>
                         

                        </Col>
              </Row>
                  
                    
         </div>
                <Table
                    rowKey="_id"
                    loading={loading}
                    columns={columns}
                    dataSource={datalist}
                    rowSelection={rowSelection}
                    pagination={pagination}
                    scroll={{ y: 400 }}
                />
            </div>
        )
    }
}

export default List;